<?php

namespace app\controller;

use think\facade\Db;
use think\facade\View;
use app\model\OpAccount;
use app\model\User;
use app\model\Items;
use app\model\ItemConsume;
use app\model\ViewItem;
use think\Model;
use app\model\Recharge;
use app\model\Channel;
use app\model\AccInfo;
use app\model\Customer;
use app\model\OperateGroup;
use app\model\OperateYeji;
class Operate
{


    // 运营

    public function accounts()
    {
        $OpAccount = new OpAccount();
        if (request()->isPost()&&input('t')=='json') {
            $name = input('post.name',0);
            $name_id = input('post.name_id',0);
            $industry_id = input('post.industry_id',0);
            $operate_id = input('post.operate_id',0);
            $channel_id = input('post.channel_id',0);
            $type = input('post.type',0);
            if ($name) {
                $wh[] = ['op.name', 'like', "%" . $name . "%"];
            }
            if ($name_id) {
                $wh[] = ['op.name_id', 'like', "%" . $name_id . "%"];
            }
            if ($industry_id) {
                $wh[] = ['op.industry_id', '=', $industry_id];
            }
            if ($channel_id) {
                $wh[] = ['op.channel_id', '=', $channel_id];
            }
            $isgroup = false;
            if ($operate_id) {
                $wh[] = ['op.operate_id', '=', $operate_id];
                $isgroup = $this->get_is_group($operate_id);
            }
            $wh[] = ['op.acc_type', '=', $type+1 ];
            
            if(session('info.is_leader') != 1 && session('info.role_id') !=1 && session('info.role_id') !=20 && $isgroup == false){
                $wh[] = ['op.operate_id','=',session('uid')];
            }
            $wh[] = ['op.id','>',0];
            $wh[] = ['op.is_banned','=',1];
           
            $list = $OpAccount->alias('op')
            ->field('op.*,ch.name channel_name,u.username operate_name,i.name industry')
            ->leftJoin('channel ch','ch.id = op.channel_id')
            ->leftJoin('user u','u.id = op.operate_id')
            ->leftJoin('industry i','i.id = op.industry_id')
            ->where($wh)->order("op.status desc, op.create_time desc")->page(input('post.page'),input('post.limit'))->select()->toArray();
            $cnt = Db::name("op_account")->alias('op')->where($wh)->count('id');
        
            foreach ($list as $k => $v) {
                $list[$k]["balance"] = number_format(floatval($v['balance']), 3);
                $list[$k]["is_launch"] = $this->is_launch($v['id']);
                $list[$k]["lv"] = $this->acc_lv($v['id']);
                // $list[$k]["lv"] = 0;
            }
                
            
            
            return json(['code' => 0, 'msg' => '', 'count' => $cnt, 'data' => $list]);
        }else{
            //获取行业
            $industry_list = Db::name('industry')->select();
            //获取端口
            $channel_list = Channel::field('id,name')->select();
            //获取运营
            $op[] = ['dept_id','=',2];
            $op[] = ['status','=',1];
            $operate = User::where($op)->field("id,username")->select();
            View::assign('industry_list',$industry_list);
            View::assign('operate_list',$operate);
            View::assign('channel_list',$channel_list);
            return view();
        }
        
    }
    function get_subset_info($v){
        
        $OpAccount = new OpAccount();
        $w1[] = ['op2.pid','=',$v['id']];
       
        if(session('info.is_leader') != 1 && session('info.role_id') !=1 && session('info.role_id') !=20){
            $w1[] = ['op2.operate_id','=',session('uid')];
        }
        $list2 = $OpAccount->alias('op2')
        ->field('op2.*,ch.name channel_name,u.username operate_name,i.name industry')
        ->leftJoin('channel ch','ch.id = op2.channel_id')
        ->leftJoin('user u','u.id = op2.operate_id')
        ->leftJoin('industry i','i.id = op2.industry_id')
        ->where($w1)->order("op2.status desc,op2.create_time desc")->select()->toArray();
       
        return $list2;
    }
    //判断账户是否投放
    function is_launch($id){
        $wh[] = ['op_account_id','=',$id];
        $wh[] = ['is_finish','=',0];
        $wh[] = ['status','=',1];
        $n = Items::where($wh)->count('id');
        
        return $n;
    }
    // 判断当前人员是否是组长，要搜索的人员是否是改组下的成员
    function get_is_group($operate_id){
        $leader = OperateGroup::where('leader',session('uid'))->count('id');
        $wh[] = ['member','like','%'.$operate_id.'%'];
        $wh[] = ['leader','=',session('uid')];
        $member = OperateGroup::where($wh)->count('id');
        if($leader > 0 && $member > 0){
            return true;
        }else{
            return false;
        }

    }

    //修改账号状态
    public function get_save_acc_status()
    {
        $item = new Items();
        if (request()->isPost()&&input('t')=='json') {
            $data = input('post.');
            if($item->is_acc_item($data['id'])){
                return json(['code' => 0, 'msg' => '当前账户下有正在投递项目，不能进行该操作']);
            }
            
            $data["update_time"] = time();
            $rs = Db::name('op_account')->save($data);
            if ($rs) {
                return json(['code' => 1, 'msg' => '提交成功']);
            } else {
                return json(['code' => 0, 'msg' => '提交失败']);
            }
        }
    }

    //添加账号
    public function acc_add()
    {
        $User = new User();
        if (request()->isPost()&&input('t')=='json') {
            $data = input('post.');
            $validate = \think\facade\Validate::rule([
                'source|账户来源' => 'require',
                'acc_type|账户类别' => 'require',
                'channel_id|渠道名称' => 'require',
                'name|账户名称' => 'require',
                'name_id|账户ID' => 'require|unique:op_account',
                'industry_id|行业' =>'require',
            ]);
            $w[] = ['channel_id','=',$data['channel_id']];
            $w[] = ['name_id','=',$data['name_id']];
            $r = OpAccount::where($w)->find();
            if(!empty($r)){
                // 验证失败 输出错误信息
                return json(['code' => 0, 'msg' => '账户ID已存在']);
            }
            if (!$validate->check($data)) {
                // 验证失败 输出错误信息
                return json(['code' => 0, 'msg' => $validate->getError()]);
            } else {
                $data["oper_name"] = session('info.username');
                $data["create_time"] = time();
                $rs = Db::name('op_account')->insert($data);
                if ($rs) {
                    log_add(1,'账户添加');
                    return json(['code' => 1, 'msg' => '提交成功']);
                } else {
                    return json(['code' => 0, 'msg' => '提交失败']);
                }
            }

        } else {
            $pid = request()->get('type');
            if (!empty($pid)) {
                $r = Db::name('op_account')->where('id', $pid)->find();
                
                View::assign('type', $pid);
                View::assign('name', $r['name']);
                View::assign('r', $r);
            } else {
                View::assign('type', 0);
            }
            //获取渠道列表
            $this->get_channel_list();
            //获取运营
            $w[] = ['role_id','in','3,18,20'];
            
            $operate_list = $User->where($w)->select()->toArray();
            
            //获取行业
            $industry_list = Db::name('industry')->select();
            
            View::assign('industry_list',$industry_list);
            View::assign('operate_list',$operate_list);
            return view();
        }
    }

    //获取行业列表
    function get_industry_list()
    {
        $list = Db::name("industry")->where('status', 1)->select();
        View::assign('industry_list', $list);
    }

    //获取渠道列表
    function get_channel_list()
    {
        $list = Db::name("channel")->where('status', 1)->select();
        View::assign('channel_list', $list);
    }

    //编辑
    public function acc_save()
    {
        $User = new User();
        $item = new Items();
        if (request()->isPost()&&input('t')=='json') {
            $data = input('post.');
            $validate = \think\facade\Validate::rule([
                'source|账户来源' => 'require',
                'acc_type|账户类别' => 'require',
                'channel_id|渠道名称' => 'require',
                'name|账号名称' => 'require',
                'name_id|账号ID' => 'require',
                'industry_id|行业' =>'require',
                
            ]);

            if (!$validate->check($data)) {
                // 验证失败 输出错误信息
                return json(['code' => 0, 'msg' => $validate->getError()]);
            } else {
                /* if($item->is_acc_item($data['id'])){
                    return json(['code' => 0, 'msg' => '当前账户下有项目，不能进行该操作']);
                } */
                $data["oper_name"] = session('info.username');
                $data["update_time"] = time();
                $rs = Db::name('op_account')->save($data);
                if ($rs) {
                    log_add(2,'账户修改');
                    return json(['code' => 1, 'msg' => '提交成功']);
                } else {
                    return json(['code' => 0, 'msg' => '提交失败']);
                }
            }
        } else {
            $id = input("get.id");
            $wh["id"] = $id;
            $rs = Db::name('op_account')->where($wh)->find();
           
            //获取渠道列表
            $this->get_channel_list();
            
            //获取运营
            $w[] = ['role_id','in','3,18,20'];
            $operate_list = $User->where($w)->select();
            //获取行业
            $industry_list = Db::name('industry')->select();
            
            View::assign('industry_list',$industry_list);
            View::assign('operate_list',$operate_list);
            View::assign('rs', $rs);
            return view();
        }
    }
    
    //添加消耗
    public function consume_add(){
        $Items = new Items();
        $ItemConsume = new ItemConsume();
        if(request()->isPost() && input('t')=='json'){
            $data = input('post.');
            $rs = $ItemConsume->get_add($data);
            if ($rs === true) {
                $data['operation_id'] = session('uid');
                $data['time'] = strtotime(date("Y-m-d",strtotime($data['time'])));
                $data['create_time'] = time();
                $data['update_time'] = time();
                $arr = $this->get_rebates($data['items_id'],$data['currency']);
                $data['consume_profit'] = $arr['profit'];
                $data['rebate'] = $arr['rebate'];
                $data['channel_rebate'] = $arr['channel_rebate'];
                Db::startTrans();
                try {
                    
                    //添加消耗记录
                    Db::name('item_consume')->save($data);
                    //跟新项目消耗累计
                    Db::name('items')->where('id', $data['items_id'])->inc('total_money', $data['currency']*1) ->update();
                    
                    $w['id'] = $data['items_id'];
                    Db::name('items')->where($w)->update(['end_time'=>time()]);
                    //跟新客户累计账户币消耗
                    $cu_id = Items::where('id',$data['items_id'])->value('customer_id');
                    Db::name('customer')->where('id',$cu_id)->inc('total_currency_consume', $data['currency']*1) ->update();
                    // 提交事务
                    Db::commit();
                    log_add(1,'添加消耗');
                    return json(['code' => 1, 'msg' => '提交成功']);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['code' => 0, 'msg' => $e->getMessage()]);
                }
            } else {
                return json(['code' => 0, 'msg' => $rs]);
            }
        }else{
            
            $data = input('get.');
            View::assign('data',$data);
            return view();
        }
    }
    //获取最后一次充值的所有返点，获取利润
    function get_rebates($item_id,$currency){
        $wh['status'] = 1;
        $wh['type'] = 2;
        $wh['items_id'] = $item_id;
        $list = Recharge::field('rebate,channel_rebate,currency')->where($wh)->order('update_time desc')->find();
        if($list){
            $profit = cny_profit($currency, $list['rebate'], $list['channel_rebate']);
            if($profit < 0){
                $profit = 0;
            }
            $arr['rebate'] = $list['rebate'];
            $arr['channel_rebate'] = $list['channel_rebate'];
            $arr['profit'] = $profit;
        }else {
            $arr['rebate'] = 0;
            $arr['channel_rebate'] = 0;
            $arr['profit'] = 0;
        }
        
        return $arr;
    }
    
    
    //获取项目对应的账户
    public function get_items_acc(){
        if(request()->isPost() && input('t')=='json'){
            $rs = ViewItem::where('item_id',input('post.id'))->find();
            if ($rs) {
                return json(['code' => 1, 'msg' => '提交成功','data'=>$rs]);
            } else {
                return json(['code' => 0, 'msg' => '但前项目未绑定账户']);
            }
        }
    }
    
    //修改消耗
    public function save_consume(){
        $Items = new Items();
        $ItemConsume = new ItemConsume();
        if(request()->isPost() && input('t') == 'json'){
            $data = input('post.');
            $rs = $ItemConsume->get_save($data);
            if ($rs === true) {
                $data['operation_id'] = session('uid');
                $data['time'] = strtotime(date("Y-m-d",strtotime($data['time'])));
                $data['update_time'] = time();
                $arr = $this->get_save_rebates($data['id'],$data['currency']);
                $data['consume_profit'] = $arr['profit'];
                $data['rebate'] = $arr['rebate'];
                $data['channel_rebate'] = $arr['channel_rebate'];
                Db::startTrans();
                try {
                    $items = ItemConsume::where('id',$data['id'])->find();
                    if($items['currency'] != $data['currency']){
                        //跟新项目消耗累计
                        $currencys = Db::name('item_consume')->where('id', $items['items_id'])->sum('currency');
                        $currencys = $currencys - $items['currency'] + $data['currency'];
                        Db::name('items')->where('id', $items['items_id'])->update(['total_money'=>$currencys]);
                        
                        //跟新客户累计账户币消耗
                        $cu_id = Items::where('id',$items['items_id'])->value('customer_id');
                        $total_currency_consume = Db::name('customer')->where('id',$cu_id)->value('total_currency_consume');
                        $total_currency_consume = $total_currency_consume - $items['currency'] + $data['currency'];
                        Db::name('customer')->where('id',$cu_id)->update(['total_currency_consume'=>$total_currency_consume]);
                    }
                    //修改消耗记录
                    Db::name('item_consume')->save($data);
                    
                    // 提交事务
                    Db::commit();
                    log_add(2,'修改消耗');
                    return json(['code' => 1, 'msg' => '提交成功']);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['code' => 0, 'msg' => $e->getMessage()]);
                }
            } else {
                return json(['code' => 0, 'msg' => $rs]);
            }
        }else{
            $id = input('get.id');
            $rs = ItemConsume::find($id);
            
            View::assign("rs",$rs);
            return view();
        }
    }
    
    function get_save_rebates($id,$currency){
        $wh['status'] = 1;
        $wh['type'] = 2;
        $wh['items_id'] = ItemConsume::where('id',$id)->value("items_id");
        $rs = Recharge::field('rebate,channel_rebate,currency')->where($wh)->order('update_time desc')->find();
        if($rs){
            $profit = cny_profit($currency, $rs['rebate'], $rs['channel_rebate']);
            if($profit < 0 ){
                $profit = 0;
            }
            $arr['rebate'] = $rs['rebate'];
            $arr['channel_rebate'] = $rs['channel_rebate'];
            $arr['profit'] = $profit;
        }else{
            $arr['rebate'] = 0;
            $arr['channel_rebate'] = 0;
            $arr['profit'] = 0;
        }
        
        return $arr;
    }
    
    
    
    
    

    //添加行业
    public function add_industry()
    {
        if (request()->isPost()) {
            $data = input("post.");
            $validate = \think\facade\Validate::rule([
                'name|行业名称' => 'require|unique:industry',
            ]);
            
            if (!$validate->check($data)) {
                // 验证失败 输出错误信息
                return json(['code' => 0, 'msg' => $validate->getError()]);
            } else {
                $rs = Db::name('industry')->save($data);
                if ($rs) {
                    return json(['code' => 1, 'msg' => '提交成功']);
                } else {
                    return json(['code' => 0, 'msg' => '提交失败']);
                }
            }
        }
    }

    //账号详情
    public function acc_info(){
        if(request()->isPost() && input('t')=='json'){
            $da = input('post.');
            if(empty($da)){
                return json(['code' => 0, 'msg' => '请输入有效的数据']);
            }
            $da['video_url'] = implode(',',$da['video_url']);
            $da['cover_url'] = implode(',',$da['cover_url']);
            
            try {
                Db::name('acc_info')->save($da);
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Throwable $e) {
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
            
        }else{
            $id = input('get.id');
            $rs = AccInfo::where('pid',$id)->find();
            if($rs['video_url']){
                $rs['video_url'] = explode(',',$rs['video_url']);
            }
            if($rs['video_url']){
                $rs['cover_url'] = explode(',',$rs['cover_url']);
            }
            $cu_list = Customer::field('id,name')->where('status',1)->select();

            View::assign('cu_list',$cu_list);
            View::assign('rs',$rs);
            return view();
        }
        

    }
   
    //账号完成率			
	// 评定完成率标准：				
	// 1.   开户中 ==============================================2%				
	// 2.   素材已准备完毕等待上传====================================5%				
	// 3   审核页与投放页面已准备完毕  =================================8%				
	// 4.   账户创建成功搭建第一阶段素材================================5%				
	// 5.   账户第一阶段素材已通过搭建第二阶段投放素材=======================10%				
	// 6.   第二阶段投放素材已通过等待投放===============================30%				
	// 7.   明确客户KPI需求；账户开始投放===============================5%				
	// 8.   账户投放达到客户要求=====================================15%				
	// 9.   账户投放续费5次以上 =====================================10%				
	// 10. 账户续费10次以上 =======================================10%				

    public function acc_lv($id){
        //账号进度
        $jindu = OpAccount::where('id',$id)->value('jindu');
        //账号审核页与投放页
        $putin = AccInfo::field("putin_url,consume_goal,form_goal")->where('pid',$id)->find();
        
        //账号是否投放
        $wh[] = ['op_account_id','=',$id];
        $wh[] = ['is_deliver','=',1];
        $wh[] = ['is_finish','=',0];
        $wh[] = ['status','=',1];
        $items = Items::where($wh)->find();
        
        $lv = 0;
        switch ($jindu) {
            case '1': //开户中
                $lv = 2;
                break;
            case '6': //素材已准备完毕
                $lv = 7;
                break;
            case '2': //素材已准备完毕
                $lv = 22;
                break;
            case '3':   //第一阶段素材已通
                $lv = 12;
                break;
            case '4':   //第二阶段投放素材已通
                $lv = 22;
                break;
            case '5':
                $lv = 52;
                break;
            
            default:
                break;
        }
        //审核页与投放页面已准备完毕
        if($putin['putin_url']){
            $lv = $lv + 5;
        }
        //已投放
        if($items['id']){
            $lv = $lv + 8;
        }
        //账户投放续费次数
        $n = 0;
        if($items['id']){
            $whh[] = ['items_id','=',$items['id']];
            $whh[] = ['op_account_id','=',$id];
            $whh[] = ['status','=',1];
            $n = Recharge::where($whh)->count('id');
        }
        //账户投放续费5次以上
        if($n >= 5){
            $lv = $lv + 10;
        }
        //账户投放续费10次以上
        if($n >= 10){
            $lv = $lv + 10;
        }
        //账户投放达到客户要求+15
        $t = strtotime(date("Y-m-d",strtotime("-1 day")));
        $w1[] = ['time','=',$t];
        $w1[] = ['items_id','=',$items['id']];
        $w1[] = ['op_account_id','=',$id];
        $consume = ItemConsume::where($w1)->find();
        if($items['type'] == 1){
            //跑消耗
            if($putin['consume_goal'] > 0 && $putin['consume_goal'] <= $consume['currency']){
                $lv = $lv + 15;
            }
        }
        if($items['type'] == 2){
            //跑表单
            if($consume['num'] > 0 ){
                $pay = $consume['currency']/$consume['num'];
            }else{
                $pay = 0;  
            }
            if($putin['form_goal'] > 0 && $putin['form_goal'] >= $pay){
                $lv = $lv + 15;
            }
        }
        return $lv.'%';
    }
    
    /**
     * 运营 小组和业绩设置
     * 
     * */
    public function group(OperateGroup $OperateGroup){
        if(request()->isPost() && input('t')=='json'){
            $arr = $OperateGroup->get_list(input('post.'));
            return json(['code' => 0, 'msg' => '', 'count' => $arr['cnt'], 'data' => $arr['list']]);
        }

        return view();
    }
    //添加小组
    public function group_add(OperateGroup $OperateGroup){
        if(request()->isPost() && input('t')=='json'){
            $r = $OperateGroup->get_add(input('post.'));
            if($r === 1){
                log_add(1,'添加小组');
                return json(['code' => 1, 'msg' => '提交成功']);
            }else{
                return json(['code' => 1, 'msg' => $r]);
            }
        }
        $wh[] = ['role_id','in','3,18,20'];
        $wh[] = ['status','=','1'];
        $acc_list = User::field('id,username')->where($wh)->select();
        
        View::assign('acc_list',$acc_list);
        return view();
    }
    function get_yy_list(){
        if(request()->isPost() && input('t')=='json'){
            $wh[] = ['role_id','in','3,18,20'];
            $wh[] = ['status','=','1'];
            $acc_list = User::field('id value,username name')->where($wh)->select();
            return json(['code' => 1, 'msg' => '',  'data' => $acc_list]);
        }
        
    }
    //修改小组
    public function group_save(OperateGroup $OperateGroup){
        if(request()->isPost() && input('t')=='json'){
            $r = $OperateGroup->get_save(input('post.'));
            if($r === 1){
                log_add(2,'修改小组');
                return json(['code' => 1, 'msg' => '提交成功']);
            }else{
                return json(['code' => 0, 'msg' => $r]);
            }
        }
        $wh[] = ['role_id','in','3,18,20'];
        $wh[] = ['status','=','1'];
        $acc_list = User::field('id,username')->where($wh)->select();
        $rs = $OperateGroup->where('id',input('get.id'))->find();

        View::assign('acc_list',$acc_list);
        View::assign('rs',$rs);
        return view();
    }
    //删除小组
    function get_yy_del(){
        if(request()->isPost() && input('t')=='json'){
            try {
                OperateGroup::destroy(input('post.id'));
                log_add(3,'删除小组');
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Throwable $th) {
                //throw $th;
                return json(['code' => 0, 'msg' => $th->getMessage()]);
            }
            
        }
    }
    //任务设置
    public function performance(OperateYeji $OperateYeji){
        if(request()->isPost() && input('t')=='json'){
            $arr = $OperateYeji->get_list(input('post.'));
            return json(['code' => 0, 'msg' => '', 'count' => 0, 'data' => $arr['list']]);
        }
        $wh[] = ['role_id','in','3,18,20'];
        $wh[] = ['status','=','1'];
        $acc_list = User::field('id,username')->where($wh)->select();

        View::assign('acc_list',$acc_list);
        return view();
    }
    //添加任务
    public function yeji_add(OperateYeji $OperateYeji){
        if(request()->isPost() && input('t')=='json'){
            $r = $OperateYeji->get_add(input('post.'));
            if($r === 1){
                log_add(1,'添加任务');
                return json(['code' => 1, 'msg' => '提交成功']);
            }else{
                return json(['code' => 1, 'msg' => $r]);
            }
        }
        $wh[] = ['role_id','in','3,18,20'];
        $wh[] = ['status','=','1'];
        $acc_list = User::field('id,username')->where($wh)->select();
        
        View::assign('acc_list',$acc_list);
        return view();
    }
    //修改任务
    public function yeji_save(OperateYeji $OperateYeji){
        if(request()->isPost() && input('t')=='json'){
            $r = $OperateYeji->get_save(input('post.'));
            if($r === 1){
                log_add(2,'修改任务');
                return json(['code' => 1, 'msg' => '提交成功']);
            }else{
                return json(['code' => 1, 'msg' => $r]);
            }
        }
        $wh[] = ['role_id','in','3,18,20'];
        $wh[] = ['status','=','1'];
        $acc_list = User::field('id,username')->where($wh)->select();
        $rs = $OperateYeji->where('id',input('get.id'))->find();
       
        View::assign('rs',$rs);
        View::assign('acc_list',$acc_list);
        return view();
    }
     //删除任务
     function get_yeji_del(){
        if(request()->isPost() && input('t')=='json'){
            try {
                OperateYeji::destroy(input('post.id'));
                log_add(3,'删除任务');
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Throwable $th) {
                //throw $th;
                return json(['code' => 0, 'msg' => $th->getMessage()]);
            }
            
        }
    }
    
    /**
     *  数据统计 
     * */
    public function stat(){
        //获取个人任务进度
        $this->get_rw_jindu();
        // 小组的任务进度
        $this->get_xz_jindu();
        $this->acc_ranking();

        return view();
    }
    //获取个人任务进度
    function get_rw_jindu(){
        $OperateYeji = new OperateYeji;
        $operate_id = session('uid');
        $t = strtotime(date("Y-m-01",time()));
        $t2 = strtotime(" +1 month -1 day");
        //个人消耗
        $xh = $OperateYeji->get_xiaohao_sum($operate_id,$t,$t2);
        //个人任务
        $wh[] = ['operate_id','=',session('uid')];
        $wh[] = ['time','=',$t];
        $rw = OperateYeji::where($wh)->value('yeji');
        //个人任务完成度
        if($rw){
            $lv = ($xh/$rw)*100;
        }else{
            $lv = 0;
        }
        $arr['lv'] = round($lv,2);
        $arr['xh'] = number_format($xh,2);
        $arr['rw'] = number_format($rw,2);
        View::assign('gr_rw',$arr);
    }
    // 小组的任务进度
    function get_xz_jindu(){
        $t = strtotime(date("Y-m-01",time()));
        $t2 = strtotime(" +1 month -1 day");
        if(session('info.is_leader') == 1 || session('info.role_id') ==1 ){
            $w1[] = ['role_id','in','3,18,20'];
            $member = User::where($w1)->column('id');
            $member = implode(',',$member);

            $w3[] = ['operate_id','=',9];
            $w3[] = ['time','=',$t];
            $rw =  OperateYeji::where($w3)->value('yeji');

            $w5[] = ['time','between',[$t,$t2]];
            $xh = ItemConsume::where($w5)->sum('currency');
        }else{
            $w[] = ['member','like',"%".session('uid').'%'];
            $member = OperateGroup::where($w)->value('member');

            $w2[] = ['operate_id','in',$member];
            $w2[] = ['time','=',$t];
            $rw =  OperateYeji::where($w2)->sum('yeji');

            $w4[] = ['time','between',[$t,$t2]];
            $w4[] = ['operation_id','in',$member];
            $xh = ItemConsume::where($w4)->sum('currency');
        }
        if($rw > 0){
            $lv = ($xh/$rw)*100;
            $arr['lv'] = round($lv,2);
            $arr['xh'] = number_format($xh,2) ;
            $arr['rw'] = number_format($rw,2) ;
        }else{
            $arr['lv'] = 0;
            $arr['xh'] = $xh;
            $arr['rw'] = 0;
        }
        
        View::assign('xz_rw',$arr);
    }
    //总消耗 （年:1，月:2，日:3）item_consume
    function get_consume_info(){
        if(request()->isPost() && input('t')=='json'){
            $t = input('post.time',3);
            $is_operate = input('post.is_operate',0);
            if($t == 1){
               
            }elseif ($t == 2){
                $m = $this->get_month();
                for ($i=0;$i<count($m);$i++){
                    $arr['x'][] = $m[$i];
                    $w[] = ['id','>',0];
                    $arr['y'][] = ItemConsume::where($w)->whereMonth('time', $m[$i]) ->sum('currency');
                    
                }
                $arr['text'] = '最近12个月消耗';
                return json(['msg' => '', 'code' => 1,'data'=>$arr]);
            }elseif ($t == 3){
                $tt = $this->get_time();
                for ($i=0;$i<count($tt);$i++){
                    $arr['x'][] = date("m-d",$tt[$i]);
                    $arr['y'][] = $this->get_day_consume($tt[$i],$is_operate);
                    $arr['y1'][] = $this->get_day_jjz($tt[$i]);
                }
                $arr['text'] = '最近30天消耗';
                return json(['msg' => '', 'code' => 1,'data'=>$arr]);
            }
            
        }
    }

    //获取最近30天时间
    function get_time(){
        $t1 = strtotime(date("Y-m-d",strtotime("-30 day"))) - 86400;
        for ($i=0;$i<30;$i++){
            $t[] = $t1 += 86400;
        }
        return $t;
    }
    //获取最近12个时间
    function get_month(){
         for ($i=11;$i>=0;$i--){
            $t[] = date("Y-m",strtotime("-$i month"));
         }
        return $t;
    }
    //获取每天的消耗
    function get_day_consume($t,$is_operate){
        $s = $t.','.($t+86400);
        //$w[] = ['time','between',$s];
        $w[] = ['time','=',$t];
        if(session('info.is_leader') == 1 || session('info.role_id') ==1 ){
            $ww[] = ['dept_id','=',2];
            $ww[] = ['status','=',1];
            $ids = User::where($ww)->column('id');
            $w[] = ['operation_id','in',$ids];
        }else{
            $w[] = ['operation_id','=',session('uid')];
        }
        if(isset($is_operate) && !empty($is_operate)){
            $w[] = ['is_operate','=',$is_operate];
        }
        $n = ItemConsume::where($w)->sum('currency');
        return $n;
    }
    //获取每天的警戒值
    function get_day_jjz($t){
        $t1 = strtotime(date("Y-m",$t));
        $days = date('t', $t1);
        $w[] = ['time','=',$t1];
        if(session('info.is_leader') == 1 || session('info.role_id') ==1 ){
            $w[] = ['operate_id','=',9];
        }else{
            $w[] = ['operate_id','=',session('uid')];
        }
        $rw = OperateYeji::where($w)->value('yeji');
        $jj = $rw/$days;
        $jj = round($jj,2);
        return $jj;
    }
    /**
     * 个人和小组消耗数据
     * */
    public function consume_top(){
        if(request()->isPost() && input('t')=='json'){
            $type = input('post.type',1);
            if($type == 1){
                //获取左天的消耗
                $t = strtotime(date("Y-m-d",strtotime("-1 day")));
                $t2 = $t+86399;
                $arr['text'] = '昨天消耗';
            }elseif ($type == 2){
                $w=date('w');//获取当前周的第几天 周日是 0 周一到周六是1-6
                $beginLastweek=strtotime('-'.($w ? $w-1 : 6).' day');//获取本周开始日期，如果$w是0是周日:-6天;其它:$w-1天
                $cur_monday=date('Y-m-d',$beginLastweek);
                $s=date('Y-m-d',strtotime("$cur_monday -7 day"));
                $e=date('Y-m-d',strtotime("$s +6 days"));
                $t = strtotime($s);
                $t2 = strtotime($e)+86399;
                $arr['text'] = '上周消耗';
            }elseif ($type == 3){
                $t = mktime(0, 0 , 0,date("m")-1,1,date("Y"));
                $t2 = mktime(23,59,59,date("m") ,0,date("Y"));
                $arr['text'] = '上月消耗';
            }elseif($type == 4){
                //自定义时间消耗排行
                $time = input('post.times');
                if($time == 0){
                    $t = strtotime(date("Y-m-d",strtotime("-1 day")));
                    $t2 = $t+86399;
                    $arr['text'] = '昨天消耗';
                }else{
                    $arr = explode('&', $time);
                    $t = strtotime($arr[0]);
                    $t2 = strtotime($arr[1])+86399;
                    $arr['text'] = $time.'消耗';
                }
                
            }
            if(session('info.is_leader') == 1 || session('info.role_id') ==1 ){
                $wh[] = ['role_id','=',18];
            }else{
                $w1[] = ['member','like','%'.session('uid').'%'];
                $ids = OperateGroup::where($w1)->value('member');
                $wh[] = ['id','in',$ids];
            }
           
            $wh[] = ['status','=',1];
            $list = User::field('id,username')->where($wh)->select();
            $is_operate = input('post.is_operate');
            foreach ($list as $k=>$v){
                $name = preg_replace('/牧唐-运营助理-/','',$v['username']);
                if(strlen($name)>9){
                    $name = preg_replace('/牧唐-运营-/','',$v['username']);
                }
                $arr['x'][] = $name;
                $arr['y'][] = $this->get_run_consume($v['id'],$t,$t2,$is_operate);
            }
            
            
            return json(['msg' => '', 'code' => 1,'data'=>$arr]);
        }
    }
    //获取需要排名的运营同学
    function get_run_consume($id,$t1,$t2,$is_operate=0){
        $s = $t1.','.$t2;
        $w[] = ['time','between',$s];
        $w[] = ['operation_id','=',$id];
        if($is_operate != 0){
            $w[] = ['is_operate','=',$is_operate];
        }
        
        $n = ItemConsume::where($w)->sum('currency');
        return $n;
    }

    //每月消耗前5名，快手，头条
    public function acc_ranking(){
        if(request()->isPost() && input('t')=='json'){
            $ks_ids = $this->get_acc_ids(1);
            $tt_ids = $this->get_acc_ids(2);
            
            $ks_list = $this->get_xiahoa_5($ks_ids);
            $tt_list = $this->get_xiahoa_5($tt_ids);
            foreach ($ks_list as $k=>$v){
                $name = preg_replace('/牧唐-运营助理-/','',$v['username']);
                if(strlen($name)>9){
                    $name = preg_replace('/牧唐-运营-/','',$v['username']);
                }
                $ks['type'] = 'bar';
                $ks['name'] = $v['name_id'].'_'.$name.'_'. $v['name'];
                $ks['data'] = [$v['num']];
                $arr['ks_list'][] = $ks;
                $tt_name = preg_replace('/牧唐-运营助理-/','',$tt_list[$k]['username']);
                if(strlen($tt_name)>9){
                    $tt_name = preg_replace('/牧唐-运营-/','',$tt_list[$k]['username']);
                }
                $tt['type'] = 'bar';
                $tt['name'] =  $tt_list[$k]['name_id'].'_'. $tt_name.'_'. $tt_list[$k]['name'];
                $tt['data'] = [$tt_list[$k]['num']];
                $arr['tt_list'][] = $tt;
            }
            
            return json(['msg' => '', 'code' => 1,'data'=>$arr]);
        }
        
    } 
    //获取消耗前5名
    function get_xiahoa_5($ids,$time=0){ 
        if($time){
            $time = explode('&',$time);
            $t1 = strtotime($time[0]);
            $t2 = strtotime($time[1]) + 86399;
        }else{
            $t1 = strtotime(date('Y-m-01',time()));
            $t2 = strtotime(date('Y-m-01',time())." +1 month -1 day") + 86399;
        }
        $w[] = ['ic.op_account_id','in',$ids];
        $w[] = ['ic.time','between',[$t1,$t2]];
    
        $list = ItemConsume::alias('ic')
        ->field('acc.name_id,sum(ic.currency) num,username,i.name')
        ->join('op_account acc','acc.id = ic.op_account_id','LEFT')
        ->join('user u','u.id = ic.operation_id','LEFT')
        ->join('industry i','i.id = acc.industry_id','LEFT')
        ->where($w)->group('ic.op_account_id')->order('num desc')->limit(5)->select()->toArray();
        
        return $list;
    }
    // 获取快手 $type=1，头条 $type=2账户
    function get_acc_ids($type){
        if($type == 1){
            $w[] = ['pid','=',2];
        }else{
            $w[] = ['pid','=',10];
        }
        $ids = Channel::where($w)->column('id');
        $w1[] = ['channel_id','in',$ids];
        $w1[] = ['is_banned','=',1];
        $acc_ids = OpAccount::where($w1)->column('id');
        return $acc_ids;
    }















}
